class GrammarsController < ApplicationController
  # GET /grammars
  # GET /grammars.json
  def index
    grammars = Grammar.all la: params[:l], cl: params[:c]

    respond_to do |format|
      format.json { render json: grammars }
    end
  end

  # GET /grammars/1
  # GET /grammars/1.json
  #def show
  #  @grammar = Grammar.find(params[:id])
  #
  #  respond_to do |format|
  #    format.html # show.html.erb
  #    format.json { render json: @grammar }
  #  end
  #end

  # GET /grammars/new
  # GET /grammars/new.json
  #def new
  #  @grammar = Grammar.new
  #
  #  respond_to do |format|
  #    format.html # new.html.erb
  #    format.json { render json: @grammar }
  #  end
  #end

  # GET /grammars/1/edit
  #def edit
  #  @grammar = Grammar.find(params[:id])
  #end

  # POST /grammars
  # POST /grammars.json
  def create
    ok = save_grammar_example params

    respond_to do |format|
      if grammar and grammar.save
        format.json { render json: @grammar, status: :created, location: @grammar }
      else
        format.json { render json: { ok: false } }
      end
    end
  end

  ## PUT /grammars/1
  ## PUT /grammars/1.json
  #def update
  #  @grammar = Grammar.find(params[:id])
  #
  #  respond_to do |format|
  #    if @grammar.update_attributes(params[:grammar])
  #      format.html { redirect_to @grammar, notice: 'Grammar was successfully updated.' }
  #      format.json { head :no_content }
  #    else
  #      format.html { render action: "edit" }
  #      format.json { render json: @grammar.errors, status: :unprocessable_entity }
  #    end
  #  end
  #end
  #
  ## DELETE /grammars/1
  ## DELETE /grammars/1.json
  #def destroy
  #  @grammar = Grammar.find(params[:id])
  #  @grammar.destroy
  #
  #  respond_to do |format|
  #    format.html { redirect_to grammars_url }
  #    format.json { head :no_content }
  #  end
  #end

  private

  def save_grammar_example params
    return false unless params[:u] && params[:c] && params[:l]
    return false unless Grammar.find(params[:g]).length == 1

    if params[:u]
      user = User.all un: params[:u]
      return false unless user.size == 1
      user = user[0]
      user_lang =  user.user_lang.index { |ul| ul.la == params[:l] and ul.cl == params[:c] }
      return false unless index > -1
      example = { co: params[:o], tr: params[:t] }
      user.user_lang[index].v[params[:g]] ||= []
      user.user_lang[index].v[params[:g]] << example
    end
  end
end
